import { createBrowserRouter, Navigate, Outlet } from "react-router-dom";
import Home from "@/pages/home";
import Login from "@/pages/login";
import Register from "@/pages/register";
import UserCenter from "@/pages/userCenter";
import BountyList from "@/pages/community/bounty";
import BountyDetail from "@/pages/community/bounty/detail";

let authToken = "lye";

export function setAuthToken(token) {
  authToken = token;
}

export function getAuthToken() {
  return authToken;
}

const AuthCheck = () => {
  return authToken ? <Outlet /> : <Navigate to="/login" replace />;
};

const GuestCheck = () => {
  return authToken ? <Navigate to="/" replace /> : <Outlet />;
};

const router = createBrowserRouter([
  {
    element: <AuthCheck />,
    children: [
      {
        path: "/",
        element: <Home />,
        children: [
          {
            index: true,
            element: <div>欢迎来到PT Tracker</div>,
          },
          {
            path: "user/:tab",
            element: <UserCenter />,
          },
          {
            path: "community/bounty",
            element: <BountyList />,
          },
          {
            path: "community/bounty/:id",
            element: <BountyDetail />,
          },
        ],
      },
    ],
  },
  {
    element: <GuestCheck />,
    children: [
      {
        path: "/login",
        element: <Login />,
      },
      {
        path: "/register",
        element: <Register />,
      },
    ],
  },
  {
    path: "*",
    element: <Navigate to="/" replace />,
  },
]);

export default router;
